import os
from PySide6.QtWidgets import (
    QFileDialog,
    QVBoxLayout,
    QLabel,
    QHBoxLayout,
    QWidget,
)
from PySide6.QtCore import Qt
from qframelesswindow import FramelessDialog
from qfluentwidgets import (
    PrimaryPushButton,
    PushButton,
    InfoBar,
    InfoBarPosition,
    TextEdit,
    CheckBox,
    SpinBox,
)
from ..data.database import db


class SettingsDialog(FramelessDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        # 创建界面元素
        self.wanted_dirs_edit = TextEdit()
        self.hated_dirs_edit = TextEdit()
        self.keil_args_edit = TextEdit()
        self.keil_include_dirs_edit = TextEdit()
        self.include_file_edit = TextEdit()
        self.keil_root_path_edit = TextEdit()
        self.keil_root_path_edit.setReadOnly(True)
        self.select_keil_root_path_button = PushButton("选择目录")
        self.use_relative_path_checkbox = CheckBox("相对路径")
        self.max_history_records_spinbox = SpinBox()
        self.max_history_records_spinbox.setRange(1, 723)
        self.max_history_records_spinbox.setValue(9)
        self.ok_button = PrimaryPushButton("确定")
        self.cancel_button = PushButton("取消")
        self.save_default_button = PushButton("设为默认")
        self.titleBar.closeBtn.hide()
        self.main_window = parent

        # 设置对话框样式
        self.setStyleSheet(
            """
            SettingsDialog {
                background-color: #fafafa;
            }
            QLabel {
                color: #333333;
                font-size: 13px;
                font-weight: 500;
                background: transparent;
                padding: 5px 0;
            }
            TextEdit {
                border: 1px solid #d0d0d0;
                border-radius: 6px;
                padding: 8px;
                font-size: 12px;
                background-color: white;
            }
        """
        )

        self.setWindowTitle("设置")

        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 23, 20, 15)
        main_layout.setSpacing(15)

        # 创建通用设置部分
        self.general_settings_frame = QWidget()
        general_settings_layout = QVBoxLayout(self.general_settings_frame)
        general_settings_layout.setContentsMargins(0, 0, 0, 0)
        general_settings_layout.setSpacing(8)

        # 并排布局：相对路径 和 最大历史记录数
        relative_and_history_layout = QHBoxLayout()
        relative_and_history_layout.setContentsMargins(0, 0, 0, 0)
        relative_and_history_layout.setSpacing(10)
        max_history_label = QLabel("最大历史记录数:")
        relative_and_history_layout.addWidget(max_history_label)
        relative_and_history_layout.addWidget(self.max_history_records_spinbox)
        relative_and_history_layout.addWidget(self.use_relative_path_checkbox)
        relative_and_history_layout.addStretch()
        general_settings_layout.addLayout(relative_and_history_layout)

        # 创建希望扫描目录部分
        self.wanted_frame = QWidget()
        wanted_layout = QVBoxLayout(self.wanted_frame)
        wanted_layout.setContentsMargins(0, 0, 0, 0)
        wanted_layout.setSpacing(8)

        wanted_label = QLabel("希望被扫描的目录（每行一个，空白表示扫描所有目录）:")
        self.wanted_dirs_edit.setPlaceholderText("例如：kernel\ninclude/linux")

        wanted_layout.addWidget(wanted_label)
        wanted_layout.addWidget(self.wanted_dirs_edit)

        # 创建忽略目录部分
        self.hated_frame = QWidget()
        hated_layout = QVBoxLayout(self.hated_frame)
        hated_layout.setContentsMargins(0, 0, 0, 0)
        hated_layout.setSpacing(8)

        hated_label = QLabel("不希望被扫描的目录（每行一个）:")
        self.hated_dirs_edit.setPlaceholderText("例如：.cache\n.git\n.vscode\nbuild")

        hated_layout.addWidget(hated_label)
        hated_layout.addWidget(self.hated_dirs_edit)

        # 创建 Keil 参数部分
        self.keil_args_frame = QWidget()
        keil_args_layout = QVBoxLayout(self.keil_args_frame)
        keil_args_layout.setContentsMargins(0, 0, 0, 0)
        keil_args_layout.setSpacing(8)

        keil_args_label = QLabel("基础编译参数（每行一个）:")
        self.keil_args_edit.setPlaceholderText(
            "例如：clang\n-Dsfr=volatile unsigned char"
        )

        keil_args_layout.addWidget(keil_args_label)
        keil_args_layout.addWidget(self.keil_args_edit)

        # 创建 Keil include 目录部分
        self.keil_include_dirs_frame = QWidget()
        keil_include_dirs_layout = QVBoxLayout(self.keil_include_dirs_frame)
        keil_include_dirs_layout.setContentsMargins(0, 0, 0, 0)
        keil_include_dirs_layout.setSpacing(8)

        keil_include_dirs_label = QLabel("Keil 模式额外包含目录（每行一个）:")
        self.keil_include_dirs_edit.setPlaceholderText(
            "例如：C:/Keil_v5/ARM/PACK/ARM/CMSIS/5.9.0/CMSIS/Core/Include"
        )

        keil_include_dirs_layout.addWidget(keil_include_dirs_label)
        keil_include_dirs_layout.addWidget(self.keil_include_dirs_edit)

        # 创建 include 文件部分
        self.include_file_frame = QWidget()
        include_file_layout = QVBoxLayout(self.include_file_frame)
        include_file_layout.setContentsMargins(0, 0, 0, 0)
        include_file_layout.setSpacing(8)

        include_file_label = QLabel("指定 include 文件（每行一个）:")
        self.include_file_edit.setPlaceholderText("例如: src/my_precompiled_header.h")

        include_file_layout.addWidget(include_file_label)
        include_file_layout.addWidget(self.include_file_edit)

        # 创建 Keil 根目录部分
        self.keil_root_path_frame = QWidget()
        keil_root_path_layout = QVBoxLayout(self.keil_root_path_frame)
        keil_root_path_layout.setContentsMargins(0, 0, 0, 0)
        keil_root_path_layout.setSpacing(8)

        keil_root_path_label = QLabel("项目根目录:")
        self.keil_root_path_edit.setPlaceholderText("默认为项目文件所在目录")

        keil_root_path_layout.addWidget(keil_root_path_label)
        keil_root_path_layout.addWidget(self.keil_root_path_edit)

        # 创建按钮区域
        button_frame = QWidget()
        button_layout = QHBoxLayout(button_frame)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(10)

        # 添加弹性空间，使按钮右对齐
        button_layout.addStretch(1)

        self.save_default_button.setFixedSize(90, 35)
        self.cancel_button.setFixedSize(80, 35)
        self.ok_button.setFixedSize(80, 35)

        button_layout.addWidget(self.save_default_button)
        button_layout.addWidget(self.select_keil_root_path_button)
        button_layout.addWidget(self.cancel_button)
        button_layout.addWidget(self.ok_button)

        # 添加所有部分到主布局
        main_layout.addWidget(self.general_settings_frame)
        main_layout.addWidget(self.wanted_frame)
        main_layout.addWidget(self.hated_frame)
        main_layout.addWidget(self.keil_args_frame)
        main_layout.addWidget(self.keil_include_dirs_frame)
        main_layout.addWidget(self.include_file_frame)
        main_layout.addWidget(self.keil_root_path_frame)
        main_layout.addStretch(1)  # 添加弹性空间
        main_layout.addWidget(button_frame)

        # 这些将由调用者根据模式控制
        self.general_settings_frame.hide()
        self.wanted_frame.hide()
        self.hated_frame.hide()
        self.keil_args_frame.hide()
        self.keil_include_dirs_frame.hide()
        self.keil_root_path_frame.hide()
        self.include_file_frame.hide()
        self.select_keil_root_path_button.hide()

        # 连接信号和槽
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)
        self.save_default_button.clicked.connect(self.save_as_default)
        self.select_keil_root_path_button.clicked.connect(self.select_keil_root_path)

    def set_settings(self, settings):
        self.wanted_dirs_edit.setPlainText("\n".join(settings.get("wanted_dirs", [])))
        self.hated_dirs_edit.setPlainText("\n".join(settings.get("hated_dirs", [])))
        self.keil_args_edit.setPlainText(
            "\n".join(settings.get("keil_base_arguments", []))
        )
        self.keil_include_dirs_edit.setPlainText(
            "\n".join(settings.get("keil_include_dirs", []))
        )
        self.include_file_edit.setPlainText(
            "\n".join(settings.get("include_files", []))
        )
        self.use_relative_path_checkbox.setChecked(
            settings.get("use_relative_path", True)
        )
        # 设置最大历史记录数，从全局配置获取
        max_history = db.get_max_history_records()
        self.max_history_records_spinbox.setValue(max_history)
        # 处理根目录显示逻辑
        root_path = settings.get("root_path", "")
        # 如果根目录为空（如默认设置中），则从当前项目路径派生以供显示
        if not root_path and self.main_window:
            mode = self.main_window.mode_selection_combo.currentText()
            if mode == "从 Keil 项目":
                project_file_path = self.main_window.path_line_edit.text()
                if project_file_path and os.path.isfile(project_file_path):
                    root_path = os.path.dirname(project_file_path).replace("\\", "/")
        self.keil_root_path_edit.setPlainText(root_path)

    def get_settings(self):
        root_path_text = self.keil_root_path_edit.toPlainText().strip()
        final_root_path = root_path_text  # 默认为文本编辑框中的当前值

        # 此逻辑仅在 Keil 模式下应用
        if (
            self.main_window
            and self.main_window.mode_selection_combo.currentText() == "从 Keil 项目"
        ):
            project_file_path = self.main_window.path_line_edit.text()
            if project_file_path and os.path.isfile(project_file_path):
                project_dir = os.path.dirname(project_file_path).replace("\\", "/")
                # 如果文本框中的路径与项目目录相同，
                # 则将其保存为空字符串以表示“使用默认行为”。
                if root_path_text == project_dir:
                    final_root_path = ""

        return {
            "wanted_dirs": [
                line for line in self.wanted_dirs_edit.toPlainText().split("\n") if line
            ],
            "hated_dirs": [
                line for line in self.hated_dirs_edit.toPlainText().split("\n") if line
            ],
            "keil_base_arguments": [
                line for line in self.keil_args_edit.toPlainText().split("\n") if line
            ],
            "keil_include_dirs": [
                line
                for line in self.keil_include_dirs_edit.toPlainText().split("\n")
                if line
            ],
            "include_files": [
                line
                for line in self.include_file_edit.toPlainText().split("\n")
                if line
            ],
            "root_path": final_root_path,
            "use_relative_path": self.use_relative_path_checkbox.isChecked(),
        }

    def save_as_default(self):
        if self.main_window and hasattr(self.main_window, "save_default_settings"):
            settings = self.get_settings()
            # 保存最大历史记录数到全局配置
            max_history = self.max_history_records_spinbox.value()
            db.set_max_history_records(max_history)
            self.main_window.save_default_settings(settings)

            # 重新加载并应用新的默认设置
            mode = self.main_window.mode_selection_combo.currentText()
            mode_key = "scan" if mode == "从目录扫描" else "keil"
            new_defaults = db.get_default_settings(mode_key)
            self.set_settings(new_defaults)

            InfoBar.success(
                title="成功",
                content="默认设置已保存并刷新",
                orient=Qt.Horizontal,
                isClosable=False,
                position=InfoBarPosition.TOP,
                duration=2000,
                parent=self,
            )

    def select_keil_root_path(self):
        current_path = self.keil_root_path_edit.toPlainText()
        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.Directory)
        dialog.setOption(QFileDialog.ShowDirsOnly, True)
        dialog.setDirectory(current_path if os.path.isdir(current_path) else "")

        if dialog.exec():
            selected_path = dialog.selectedFiles()[0].replace("\\", "/")
            self.keil_root_path_edit.setText(selected_path)
